import { PrismaClient } from "@prisma/client";
import { FriendRequestInput } from "../dto/friend.dto";
import { HttpError } from "../utils/httpError";
import { ErrorCode } from "../constants/errorCode";
import { NotificationType } from "../constants/notificationType";
import * as conversationService from './conversation.service';
import { console } from "inspector";

const prisma = new PrismaClient();

export const sendFriendRequest = async (
  user: { id: number, username: string },
  input: FriendRequestInput
) => {
  const userId = Number(user.id);
  if (userId === input.friend_id) {
    throw new HttpError(ErrorCode.CONFLICT, 400, "不能加自己为好友");
  }
  const existing = await prisma.friends.findFirst({
    where: {
      OR: [
        { user_id: userId, friend_id: input.friend_id },
        { user_id: input.friend_id, friend_id: userId },
      ],
    },
  });

  if (existing) {
    throw new HttpError(
      ErrorCode.CONFLICT,
      409,
      "你们之间已存在好友关系或请求"
    );
  }

  await prisma.notifications.create({
    data: {
      user_id: input.friend_id,
      type: NotificationType.FRIEND_REQUEST,
      content: `${user.username} 请求加你为好友`,
    }
  });

  return prisma.friends.create({
    data: {
      user_id: userId,
      friend_id: input.friend_id,
      remark: input.remark,
      status: 0, // pending
    },
  });
};

export const acceptFriendRequest = async (
  userId: number,
  requestId: number
) => {
  const request = await prisma.friends.findUnique({ where: { id: requestId } });

  if (!request || Number(request.friend_id) !== userId || request.status !== 0) {
    throw new HttpError(ErrorCode.FORBIDDEN, 403, "无效的请求");
  }

  await prisma.friends.update({
    where: { id: requestId },
    data: { status: 1 },
  });

  // 创建对向关系
  await prisma.friends.create({
    data: {
      user_id: userId,
      friend_id: request.user_id,
      remark: request.remark,
      status: 1,
    },
  });

  // ✅ 自动创建私聊会话（双方）
  await conversationService.createOrUpdateConversation({
    user_id: userId,
    target_id: Number(request.user_id),
    type: 1
  });

  await conversationService.createOrUpdateConversation({
    user_id: Number(request.user_id),
    target_id: userId,
    type: 1
  });
  
};

export const getFriendList = async (userId: number) => {
  const friends = await prisma.friends.findMany({
    where: {
      user_id: userId,
      status: 1,
    },
    include: {
      users_friends_friend_idTousers: {
        select: { id: true, username: true, avatar: true },
      },
    },
  });

  return friends.map((f) => f.users_friends_friend_idTousers);
};

export const getFriendRequests = async (userId: number) => {
  const requests = await prisma.friends.findMany({
    where: {
      friend_id: userId,
      status: 0,
    },
    include: {
      users_friends_user_idTousers: {
        select: { id: true, username: true, avatar: true },
      },
    },
  });

  return requests.map((r) => ({
    id: r.id,
    remark: r.remark,
    user: r.users_friends_user_idTousers,
  }));
};

export const deleteFriend = async (userId: number, targetId: number) => {
  await prisma.friends.deleteMany({
    where: {
      OR: [
        { user_id: userId, friend_id: targetId },
        { user_id: targetId, friend_id: userId },
      ],
    },
  });
};
